import { getCampusTrainingData, getSchoolZoneEnrollments } from '@/api/campus/campus'
import { addFollowUp, getFollowUp, Info, updateFollowUp } from '@/api/campus/guidance'
export default {
  name: 'FollowUpDialog',
  props: {
    currentRow: {
      type: Object,
      default: () => ({})
    },
    isDetail: {
      type: Boolean,
      default: false
    },
    editData: {
      type: Object,
      default: null
    }
  },
  data() {
    return {
      loading: false,
      trainingDataLoading: false,
      dataForm: this.getInitialFormData(),
      rules: {
        followUpDate: [{ required: true, message: '请选择跟进时间', trigger: 'change' }],
        enrollmentInfo: [{ required: true, message: '请输入落地辅导前招生情况', trigger: 'blur' }],
        totalCareCount: [{ type: 'number', min: 0, message: '托管总人数必须是大于等于0的数字', trigger: 'blur' }],
        lunchCareCount: [{ type: 'number', min: 0, message: '午托人数必须是大于等于0的数字', trigger: 'blur' }],
        eveningCareCount: [{ type: 'number', min: 0, message: '晚托人数必须是大于等于0的数字', trigger: 'blur' }],
        fullCareCount: [{ type: 'number', min: 0, message: '全托人数必须是大于等于0的数字', trigger: 'blur' }],
        expectedIncome: [{ validator: this.validateAmount, trigger: 'blur' }],
        lunchCareFee: [{ validator: this.validateAmount, trigger: 'blur' }],
        lunchFeeCycle: [{ required: true, message: '请选择午托收费周期', trigger: 'change' }],
        eveningCareFee: [{ validator: this.validateAmount, trigger: 'blur' }],
        eveningFeeCycle: [{ required: true, message: '请选择晚托收费周期', trigger: 'change' }],
        fullCareFee: [{ validator: this.validateAmount, trigger: 'blur' }],
        fullFeeCycle: [{ required: true, message: '请选择全托收费周期', trigger: 'change' }],
        problemsSolved: [{ required: true, message: '请输入本次辅导为校区梳理解决的问题', trigger: 'blur' }, { min: 10, max: 1000, message: '问题描述长度在 10 到 1000 个字符', trigger: 'blur' }],
        currentProblems: [{ required: true, message: '请输入校区目前运营还有哪些问题', trigger: 'blur' }],
        hasOpeningCalendar: [{ required: true, message: '请选择校区是否有制作开业行事历', trigger: 'change' }],

        satisfaction: [{ required: true, message: '请选择满意度评价', trigger: 'change' }]
      }
    }
  },
  computed: {
    pageTitle() {
      return this.isDetail ? '回访详情' : this.editData ? '编辑回访' : '开业辅导回访记录'
    },
    isEditMode() {
      return !!this.editData
    },
    formatOpenDate() {
      const openingDate = this.currentRow && this.currentRow.openingDate
      if (openingDate) {
        const date = new Date(openingDate)
        return !isNaN(date.getTime()) ? date.toISOString().split('T')[0] : '暂无开业日期'
      }
      return '暂无开业日期'
    }
  },
  watch: {
    'dataForm.lunchCareCount': function () {
      this.calculateTotalCareCount()
    },
    'dataForm.eveningCareCount': function () {
      this.calculateTotalCareCount()
    },
    'dataForm.fullCareCount': function () {
      this.calculateTotalCareCount()
    }
  },
  methods: {
    // 获取初始表单数据
    getInitialFormData() {
      return {
        id: '',
        campusId: '',
        followUpDate: this.normalizeDateTimeString(new Date()),
        guidanceDates: '',
        enrollmentInfo: '',
        lunchCareCount: 0,
        eveningCareCount: 0,
        fullCareCount: 0,
        totalCareCount: 0,
        lunchCareFee: '',
        lunchFeeCycle: 'month', // 午托收费周期，默认按月
        eveningCareFee: '',
        eveningFeeCycle: 'month', // 晚托收费周期，默认按月
        fullCareFee: '',
        fullFeeCycle: 'month', // 全托收费周期，默认按月
        expectedIncome: '',
        otherServices: [],
        teacherCount: 0,
        studentCount: 0,
        classCount: 0,
        systemUsage: [],
        otherSystem: '',
        problemsSolved: '',
        currentProblems: '',
        hasOpeningCalendar: '',
        additionalContent: '',
        trainingData: [],
        satisfaction: 0,
        remark: '',
        guidanceId: ''
      }
    },

    // 自动计算托管总人数
    calculateTotalCareCount() {
      const lunch = Number(this.dataForm.lunchCareCount) || 0
      const evening = Number(this.dataForm.eveningCareCount) || 0
      const full = Number(this.dataForm.fullCareCount) || 0
      this.dataForm.totalCareCount = lunch + evening + full
    },

    // 金额字段输入（不进行格式化，仅设置原始值并触发计算）
    onAmountInput(field, value) {
      this.dataForm[field] = typeof value === 'string' ? value : String(value || '')
      if (['lunchCareFee', 'eveningCareFee', 'fullCareFee'].includes(field)) {
        this.calculateMonthlyIncome()
      }
    },

    // 其他服务收费输入（不格式化）
    onOtherServiceFeeInput(index, value) {
      const arr = this.dataForm.otherServices || []
      if (arr[index]) {
        arr[index].fee = typeof value === 'string' ? value : String(value || '')
      }
      this.calculateMonthlyIncome()
    },

    // 布尔值转换工具方法
    convertBooleanFields(data, toBoolean = false) {
      const booleanFields = ['hasOpeningCalendar']
      const result = { ...data }

      booleanFields.forEach(field => {
        if (toBoolean) {
          result[field] = data[field] === 'true' || data[field] === true
        } else {
          result[field] = data[field] === true || data[field] === 'true' ? 'true' : 'false'
        }
      })

      return result
    },

    // 金额字段转换工具方法
    convertAmountFields(data, toString = false) {
      const amountFields = ['lunchCareFee', 'eveningCareFee', 'fullCareFee', 'expectedIncome']
      const result = { ...data }

      amountFields.forEach(field => {
        if (toString) {
          result[field] = data[field] ? data[field].toString() : ''
        } else {
          result[field] = data[field] ? parseFloat(data[field]) : 0
        }
      })

      return result
    },

    // 解析其他收费项目为数组，并规范字段类型
    parseOtherServices(val) {
      if (!val) return []
      try {
        const arr = typeof val === 'string' ? JSON.parse(val) : val
        if (!Array.isArray(arr)) return []
        return arr.map(item => ({
          serviceName: item.serviceName,
          studentCount: Number(item.studentCount) || 0,
          fee: item.fee !== undefined && item.fee !== null ? String(item.fee) : '',
          feeCycle: item.feeCycle === 'semester' ? 'semester' : 'month'
        }))
      } catch (e) {
        console.warn('解析其他收费项目失败:', e)
        return []
      }
    },

    // 统一的金额格式化方法（保留工具但不在输入中使用）
    formatAmount(value, maxValue = 999999.99) {
      let formattedValue = value.replace(/[\^\d.]/g, '')
      const parts = formattedValue.split('.')

      if (parts.length > 2) {
        formattedValue = parts[0] + '.' + parts.slice(1).join('')
      }

      if (parts.length === 2 && parts[1].length > 2) {
        formattedValue = parts[0] + '.' + parts[1].substring(0, 2)
      }

      const numValue = parseFloat(formattedValue)
      if (!isNaN(numValue) && numValue > maxValue) {
        formattedValue = maxValue.toString()
      }

      return formattedValue
    },

    // 解析辅导日期（兼容数组、JSON 字符串、逗号/中文分隔字符串）
    parseTutorialDate(tutorialDate) {
      if (!tutorialDate) return ''
      try {
        // 数组直接处理
        if (Array.isArray(tutorialDate)) {
          const arr = tutorialDate.map(d => String(d).trim()).filter(Boolean)
          return arr.length > 0 ? arr.join('、') : ''
        }
        // 字符串：尝试 JSON 解析，否则按分隔符切分
        if (typeof tutorialDate === 'string') {
          const str = tutorialDate.trim()
          if (!str) return ''
          let arr = []
          // 优先尝试解析为 JSON 数组字符串
          try {
            const parsed = JSON.parse(str)
            if (Array.isArray(parsed)) {
              arr = parsed
            }
          } catch (e) {
            // 非 JSON 字符串，按常见分隔符拆分：逗号、顿号、中文分隔符、空白
            arr = str.split(/[\,\u3001、\s]+/)
          }
          arr = arr.map(d => String(d).trim()).filter(Boolean)
          return arr.length > 0 ? arr.join('、') : ''
        }
        // 其他类型不支持
        return ''
      } catch (error) {
        console.warn('解析辅导日期失败:', error)
        return ''
      }
    },

    // 日期时间格式化方法
    formatDateTime(date) {
      const d = date instanceof Date ? date : new Date(date)
      if (isNaN(d.getTime())) return ''
      const pad = n => String(n).padStart(2, '0')
      const yyyy = d.getFullYear()
      const MM = pad(d.getMonth() + 1)
      const dd = pad(d.getDate())
      const HH = pad(d.getHours())
      const mm = pad(d.getMinutes())
      const ss = pad(d.getSeconds())
      return `${yyyy}-${MM}-${dd} ${HH}:${mm}:${ss}`
    },

    // 规范化日期时间为 'yyyy-MM-dd HH:mm:ss' 字符串，防止 el-date-picker 接收非字符串导致 match 错误
    normalizeDateTimeString(val) {
      if (!val) return ''
      if (typeof val === 'string') {
        const str = val.trim()
        // 若已是 'YYYY-MM-DD' 或 'YYYY-MM-DD HH:mm:ss'，直接使用（补全缺失的时间部分）
        if (/^\d{4}-\d{2}-\d{2}$/.test(str)) return `${str} 00:00:00`
        if (/^\d{4}-\d{2}-\d{2}\s+\d{2}:\d{2}:\d{2}$/.test(str)) return str
        // 尝试解析其他字符串格式
        const d = new Date(str.replace(/-/g, '/'))
        return isNaN(d.getTime()) ? '' : this.formatDateTime(d)
      }
      if (typeof val === 'number') {
        const d = new Date(val)
        return isNaN(d.getTime()) ? '' : this.formatDateTime(d)
      }
      if (val instanceof Date) {
        return isNaN(val.getTime()) ? '' : this.formatDateTime(val)
      }
      return ''
    },

    // 显示添加回访对话框
    async showFollowUpDialog(row, isEdit = false) {
      console.log(row, isEdit)
      this.currentRow = row
      // 依赖父组件传入的 isDetail，避免在子组件内覆盖
      this.resetForm()

      // 正确映射 guidanceId 与 campusId
      const guidanceId = this.currentRow && (this.currentRow.id || this.currentRow.guidanceId)
      const campusId = this.currentRow && this.currentRow.campusId

      if (guidanceId) {
        this.dataForm.guidanceId = guidanceId
      }
      if (campusId) {
        this.dataForm.campusId = campusId
      }
      this.dataForm.guidanceDates = this.parseTutorialDate(this.currentRow && this.currentRow.guidanceDates)

      // 如果是编辑模式，先加载回访详情数据
      if (isEdit && this.editData) {
        await this.fillEditData()
        // 编辑模式下也要加载最新的参训数据
        if (campusId) {
          await this.loadTrainingData()
        }
      } else {
        // 添加模式：预填招生统计与收费字段（来源于主列表行数据）
        try {
          const mapping = {
            totalCareCount: row && row.totalCareCount,
            lunchCareCount: row && row.lunchCareCount,
            eveningCareCount: row && row.eveningCareCount,
            fullCareCount: row && row.fullCareCount,
            lunchCareFee: row && row.lunchCareFee,
            eveningCareFee: row && row.eveningCareFee,
            fullCareFee: row && row.fullCareFee,
            lunchFeeCycle: row && row.lunchFeeCycle,
            eveningFeeCycle: row && row.eveningFeeCycle,
            fullFeeCycle: row && row.fullFeeCycle,
            otherServices: row && row.otherServices,
            enrollmentInfo: row && row.enrollmentInfo
          }

          Object.keys(mapping).forEach(key => {
            const val = mapping[key]
            if (val !== undefined && val !== null) {
              if (['lunchCareFee', 'eveningCareFee', 'fullCareFee'].includes(key)) {
                this.dataForm[key] = this.formatAmount(String(val))
              } else if (key === 'otherServices') {
                this.dataForm.otherServices = this.parseOtherServices(val)
              } else {
                this.dataForm[key] = val
              }
            }
          })
          // 预填后重新计算预计收入
          this.calculateMonthlyIncome()
        } catch (e) {
          console.warn('预填招生统计字段失败:', e)
        }

        await this.loadSchoolZoneData()
        // 页面加载完成后自动加载校区参训数据
        if (campusId) {
          await this.loadTrainingData()
        }
      }
    },

    // 重置表单
    resetForm() {
      this.dataForm = {
        ...this.getInitialFormData(),
        // 修复：使用campusId而不是id
        campusId: this.currentRow && this.currentRow.campusId,
        followUpDate: this.normalizeDateTimeString(new Date()),
        guidanceDates: this.parseTutorialDate(this.currentRow && this.currentRow.tutorialDate)
      }

      this.$nextTick(() => {
        this.$refs.elForm && this.$refs.elForm.clearValidate()
      })
    },

    // 加载校区数据（合并基础数据和培训数据加载）
    async loadSchoolZoneData() {
      if (!this.dataForm.campusId) return

      this.trainingDataLoading = true
      try {
        const { data } = await getSchoolZoneEnrollments(this.dataForm.campusId)
        if (data) {
          // 字段映射：后端返回teacherNum/studentNum/classNum，前端使用teacherCount/studentCount/classCount
          Object.assign(this.dataForm, {
            teacherCount: data.teacherNum || 0, // 在职老师数量
            studentCount: data.studentNum || 0, // 在校学生数量
            classCount: data.classNum || 0, // 创建班级数量
            trainingData: data.trainingData || []
          })
        }
      } catch (error) {
        console.error('获取校区数据失败:', error)
        this.dataForm.trainingData = []
      } finally {
        this.trainingDataLoading = false
      }
    },

    // 加载校区招生数据（模板中引用的方法）
    async loadSchoolZoneEnrollments() {
      if (!this.dataForm.campusId) {
        this.$message.warning('请先选择校区')
        return
      }

      this.loading = true
      try {
        const { data } = await getSchoolZoneEnrollments(this.dataForm.campusId)
        if (data) {
          // 字段映射：后端返回teacherNum/studentNum/classNum，前端使用teacherCount/studentCount/classCount
          Object.assign(this.dataForm, {
            teacherCount: data.teacherNum || 0, // 在职老师数量
            studentCount: data.studentNum || 0, // 在校学生数量
            classCount: data.classNum || 0 // 创建班级数量
          })
          this.$message.success('基础数据刷新成功')
        }
      } catch (error) {
        console.error('获取校区招生数据失败:', error)
        this.$message.error('获取基础数据失败')
      } finally {
        this.loading = false
      }
    },

    // 加载培训数据（模板中引用的方法）
    async loadTrainingData() {
      if (!this.dataForm.campusId) {
        this.$message.warning('请先选择校区')
        return
      }

      this.trainingDataLoading = true
      try {
        const { data } = await getCampusTrainingData(this.dataForm.campusId)
        if (data && data.length > 0) {
          this.dataForm.trainingData = data
        } else {
          this.dataForm.trainingData = []
        }
      } catch (error) {
        console.error('获取培训数据失败:', error)
        this.$message.error('获取参训数据失败')
        this.dataForm.trainingData = []
      } finally {
        this.trainingDataLoading = false
      }
    },

    // 填充编辑数据
    async fillEditData() {
      if (!this.editData) return

      // 使用工具方法进行数据转换
      const convertedData = this.convertBooleanFields(this.editData, false)
      const amountConvertedData = this.convertAmountFields(convertedData, true)

      Object.assign(this.dataForm, {
        ...amountConvertedData,
        id: this.editData.id,
        followUpDate: this.normalizeDateTimeString(this.editData.followUpDate),
        additionalContent: this.editData.additionalContent || this.editData.enrollmentActivityRemark,
        otherServices: this.parseOtherServices(this.editData.otherServices)
      })

      // 编辑数据填充后重新计算月收入
      this.calculateMonthlyIncome()
    },

    // 返回上一页
    goBack() {
      this.$emit('close')
    },

    // 添加其他服务项目
    addOtherService() {
      this.dataForm.otherServices.push({
        serviceName: '',
        studentCount: 0,
        fee: '',
        feeCycle: 'month' // 默认按月收费
      })
    },

    // 删除其他服务项目
    removeOtherService(index) {
      this.dataForm.otherServices.splice(index, 1)
      // 删除其他服务后重新计算月收入
      this.calculateMonthlyIncome()
    },

    // 其他服务收费格式化
    formatOtherServiceFee(index, value) {
      this.dataForm.otherServices[index].fee = this.formatAmount(value)
      // 其他服务收费变化时重新计算月收入
      this.calculateMonthlyIncome()
    },

    // 金额输入格式化
    formatAmountInput(field, value) {
      const maxValue = field === 'expectedIncome' ? 9999999.99 : 999999.99
      this.dataForm[field] = this.formatAmount(value, maxValue)

      // 如果修改的是收费相关字段，自动计算预计月收入
      if (['lunchCareFee', 'eveningCareFee', 'fullCareFee'].includes(field)) {
        this.calculateMonthlyIncome()
      }
    },

    // 计算预计月收入
    calculateMonthlyIncome() {
      // 先计算托管总人数
      this.calculateTotalCareCount()

      let monthlyIncome = 0

      // 午托收费（转换为月收入）× 午托人数
      if (this.dataForm.lunchCareFee) {
        const lunchFee = parseFloat(this.dataForm.lunchCareFee) || 0
        const lunchCount = this.dataForm.lunchCareCount || 0
        let monthlyLunchFee = 0

        if (this.dataForm.lunchFeeCycle === 'semester') {
          monthlyLunchFee = lunchFee / 4.5
        } else {
          monthlyLunchFee = lunchFee
        }
        monthlyIncome += monthlyLunchFee * lunchCount
      }

      // 晚托收费（转换为月收入）× 晚托人数
      if (this.dataForm.eveningCareFee) {
        const eveningFee = parseFloat(this.dataForm.eveningCareFee) || 0
        const eveningCount = this.dataForm.eveningCareCount || 0
        let monthlyEveningFee = 0

        if (this.dataForm.eveningFeeCycle === 'semester') {
          monthlyEveningFee = eveningFee / 4.5
        } else {
          monthlyEveningFee = eveningFee
        }
        monthlyIncome += monthlyEveningFee * eveningCount
      }

      // 全托收费（转换为月收入）× 全托人数
      if (this.dataForm.fullCareFee) {
        const fullFee = parseFloat(this.dataForm.fullCareFee) || 0
        const fullCount = this.dataForm.fullCareCount || 0
        let monthlyFullFee = 0

        if (this.dataForm.fullFeeCycle === 'semester') {
          monthlyFullFee = fullFee / 4.5
        } else {
          monthlyFullFee = fullFee
        }
        monthlyIncome += monthlyFullFee * fullCount
      }

      // 其他服务收费（转换为月收入）× 其他服务人数
      if (this.dataForm.otherServices && this.dataForm.otherServices.length > 0) {
        this.dataForm.otherServices.forEach(service => {
          if (service.fee) {
            const serviceFee = parseFloat(service.fee) || 0
            const serviceCount = service.studentCount || 0
            let monthlyServiceFee = 0

            if (service.feeCycle === 'semester') {
              monthlyServiceFee = serviceFee / 4.5
            } else {
              monthlyServiceFee = serviceFee
            }
            monthlyIncome += monthlyServiceFee * serviceCount
          }
        })
      }

      // 更新预计月收入，保留2位小数
      this.dataForm.expectedIncome = monthlyIncome > 0 ? monthlyIncome.toFixed(2) : ''
    },

    // 金额验证器
    validateAmount(rule, value, callback) {
      if (!value || value === '') {
        callback() // 允许空值
        return
      }

      // 检查是否为有效的数字格式
      const amountRegex = /^\d+(\.\d{1,2})?$/
      if (!amountRegex.test(value)) {
        callback(new Error('请输入有效的金额格式（最多保留2位小数）'))
        return
      }

      const numValue = parseFloat(value)
      if (isNaN(numValue)) {
        callback(new Error('请输入有效的数字'))
        return
      }

      if (numValue < 0) {
        callback(new Error('金额不能为负数'))
        return
      }

      // 根据字段设置不同的最大值
      const maxValue = rule.field === 'expectedIncome' ? 9999999.99 : 999999.99
      if (numValue > maxValue) {
        callback(new Error(`金额不能超过${maxValue}元`))
        return
      }

      callback()
    },

    // 准备提交数据
    prepareSubmitData() {
      const booleanConverted = this.convertBooleanFields(this.dataForm, true)
      const amountConverted = this.convertAmountFields(booleanConverted, false)

      return {
        ...amountConverted,
        id: this.dataForm.id || undefined,
        guidanceId: this.dataForm.guidanceId,
        trainingData: this.dataForm.trainingData || [], // 直接传递数组，不转换为JSON字符串
        otherServices: this.dataForm.otherServices.map(service => ({
          serviceName: service.serviceName,
          studentCount: service.studentCount || 0,
          fee: service.fee ? parseFloat(service.fee) : 0,
          feeCycle: service.feeCycle || 'month'
        }))
      }
    },

    // 加载回访详情数据
    async loadFollowUpDetail(guidanceId) {
      this.loading = true
      try {
        const response = await getFollowUp(guidanceId)
        if (response && response.data) {
          const data = response.data
          const convertedData = this.convertBooleanFields(data, false)
          const amountConvertedData = this.convertAmountFields(convertedData, true)

          // 优先使用回访详情中的 guidanceDates
          const detailGuidanceDates = this.parseTutorialDate(data.guidanceDates)
          let resolvedGuidanceDates = detailGuidanceDates

          // 回退到当前行的 guidanceDates 或 tutorialDate
          if (!resolvedGuidanceDates) {
            const fromRow = this.currentRow && (this.currentRow.guidanceDates || this.currentRow.tutorialDate)
            resolvedGuidanceDates = this.parseTutorialDate(fromRow)
          }

          // 仍为空则补取开业辅导基础详情 Info
          if (!resolvedGuidanceDates && guidanceId) {
            try {
              const infoRes = await Info(guidanceId)
              const infoData = infoRes && infoRes.data
              resolvedGuidanceDates = this.parseTutorialDate(infoData && (infoData.guidanceDates || infoData.tutorialDate || infoData.openDate))
            } catch (e) {
              console.warn('获取开业辅导基础详情失败:', e)
            }
          }

          Object.assign(this.dataForm, {
            ...amountConvertedData,
            id: data.id,
            guidanceId: data.guidanceId,
            campusId: data.campusId,
            followUpDate: this.normalizeDateTimeString(data.followUpDate),
            guidanceDates: resolvedGuidanceDates,
            enrollmentInfo: data.enrollmentInfo,
            totalCareCount: data.totalCareCount || 0,
            lunchCareCount: data.lunchCareCount || 0,
            eveningCareCount: data.eveningCareCount || 0,
            fullCareCount: data.fullCareCount || 0,
            lunchFeeCycle: data.lunchFeeCycle || 'month',
            eveningFeeCycle: data.eveningFeeCycle || 'month',
            fullFeeCycle: data.fullFeeCycle || 'month',
            otherServices: this.parseOtherServices(data.otherServices),
            teacherCount: data.teacherCount || 0,
            studentCount: data.studentCount || 0,
            classCount: data.classCount || 0,
            trainingData: data.trainingData || [],
            problemsSolved: data.problemsSolved,
            currentProblems: data.currentProblems,
            additionalContent: data.additionalContent,
            satisfaction: data.satisfaction || 0,
            remark: data.remark
          })

          this.calculateMonthlyIncome()

          if (data.campusId) {
            await this.loadTrainingData()
          }
        }
      } catch (error) {
        console.error('获取回访详情失败:', error)
        this.$message.error('获取回访详情失败')
      } finally {
        this.loading = false
      }
    },

    // 满意度评价变化处理
    onSatisfactionChange(value) {
      // 当评分变化时触发，用于实时更新显示
      this.$forceUpdate()
    },

    // 获取满意度评价标签
    getSatisfactionLabel() {
      const rating = this.dataForm.satisfaction
      if (rating >= 1 && rating <= 2) {
        return '不满意'
      } else if (rating >= 3 && rating <= 4) {
        return '一般'
      } else if (rating >= 5 && rating <= 7) {
        return '很满意'
      } else if (rating >= 8 && rating <= 10) {
        return '非常满意'
      }
      return ''
    },

    // 获取满意度评价标签样式类
    getSatisfactionLabelClass() {
      const rating = this.dataForm.satisfaction
      if (rating >= 1 && rating <= 2) {
        return 'label-unsatisfied'
      } else if (rating >= 3 && rating <= 4) {
        return 'label-average'
      } else if (rating >= 5 && rating <= 7) {
        return 'label-satisfied'
      } else if (rating >= 8 && rating <= 10) {
        return 'label-very-satisfied'
      }
      return ''
    },

    // 获取满意度评价标签内联样式（备用方案）
    getSatisfactionLabelStyle() {
      const rating = this.dataForm.satisfaction
      const baseStyle = {
        fontSize: '14px',
        fontWeight: '600',
        padding: '4px 8px',
        borderRadius: '4px',
        color: 'white'
      }

      if (rating >= 1 && rating <= 2) {
        return { ...baseStyle, backgroundColor: '#f56c6c' }
      } else if (rating >= 3 && rating <= 4) {
        return { ...baseStyle, backgroundColor: '#e6a23c' }
      } else if (rating >= 5 && rating <= 7) {
        return { ...baseStyle, backgroundColor: '#67c23a' }
      } else if (rating >= 8 && rating <= 10) {
        return { ...baseStyle, backgroundColor: '#409eff' }
      }
      return baseStyle
    },

    // 提交表单
    async dataFormSubmit() {
      const valid = await this.$refs.elForm.validate().catch(() => false)
      if (!valid) {
        this.$message.warning('请完善必填信息')
        return
      }

      this.loading = true
      try {
        const submitData = this.prepareSubmitData()
        // 使用开业辅导记录的主键ID，而不是校区ID
        const guidanceId = this.currentRow && this.currentRow.id

        if (!guidanceId) {
          throw new Error('开业辅导ID不能为空')
        }

        let res
        if (this.isEditMode) {
          res = await updateFollowUp(guidanceId, submitData)
        } else {
          res = await addFollowUp(guidanceId, submitData)
        }

        if (res && res.code === 200) {
          this.$message.success(this.isEditMode ? '更新成功' : '添加成功')
          this.$emit('refresh')
          this.goBack()
        } else {
          throw new Error((res && res.message) || '操作失败')
        }
      } catch (error) {
        console.error('提交失败:', error)
        let errorMessage = this.isEditMode ? '更新失败' : '添加失败'

        // 处理不同类型的错误
        if (error && error.response) {
          // HTTP错误响应
          const responseData = error.response.data || {}
          errorMessage = responseData.message || responseData.msg || `请求失败 (${error.response.status})`
        } else if (error && error.message) {
          // JavaScript Error对象
          errorMessage = error.message
        } else if (typeof error === 'string') {
          // 字符串错误
          errorMessage = error
        } else if (error && typeof error === 'object') {
          // 其他对象类型错误
          errorMessage = JSON.stringify(error)
        }

        this.$message.error(errorMessage)
      } finally {
        this.loading = false
      }
    }
  }
}
